// 初始化three.js的基础环境
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { CSS3DRenderer } from 'three/addons/renderers/CSS3DRenderer.js'
export let scene, camera, renderer, controls, css3DRenderer;

// 初始化函数（场景 摄像机 渲染器）
(function init() {
  scene = new THREE.Scene()
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.set(0, 0, 0.1)
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)
})();

// 创建轨道控制器
(function createControls() {
  controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true
  controls.dampingFactor = 0.25
  controls.minPolarAngle = 0.25 * Math.PI
  controls.enableZoom = false
})();

// 创建坐标轴辅助对象
(function createHelper() {
  // const axesHelper = new THREE.AxesHelper(5)
  // scene.add(axesHelper)
})();

// dom渲染
(function create3dRenderer() {
  css3DRenderer = new CSS3DRenderer()
  css3DRenderer.setSize(window.innerWidth, window.innerHeight)
  css3DRenderer.domElement.style.position = 'fixed'
  css3DRenderer.domElement.style.left = '0'
  css3DRenderer.domElement.style.top = '0'
  css3DRenderer.domElement.style.pointerEvents = 'none'
  document.body.appendChild(css3DRenderer.domElement)
})();

// 循环调用渲染函数
(function renderLoop() {
  renderer.render(scene, camera)
  controls.update()
  css3DRenderer.render(scene, camera)
  requestAnimationFrame(renderLoop)
})();


// 窗口自适应
(function resizeRender() {
  window.addEventListener('resize', () => {
    renderer.setSize(window.innerWidth, window.innerHeight)
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
  })
})()